﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace DBUtility
{
    public class CFileUpload
    {
        private FileUpload _fileUpload;
        private string imgurl;
        private string _savePath;
        private string _LastUploadedFile = string.Empty;
        private bool _AutoGenFileName = false;
        public string LastUploadedFile { get { return _LastUploadedFile; } }

        private string PICTURE_FILE = "[.gif.png.jpeg.jpg.bmp]";
        private string ZIP_FILE = "[.zip.rar]";
        private string MUILT_MEDIA_FILE = "[.mpeg.mpg.fla.exe.wma]";

        private int IMG_MAX_WIDTH = 0;//未指定宽度 
        private int IMG_MAX_HEIGHT = 0;//未指定高度 

        /// <summary> 
        /// 构造函数 
        /// </summary> 
        /// <param name="fileUpload">Asp.net FileUpload对象</param> 
        /// <param name="savePath">保存目录，不包含文件名</param> 
        /// <param name="autoGenFileName">自动生成文件名</param> 
        public CFileUpload(string imgurls, string savePath, bool autoGenFileName)
        {
            _savePath = savePath;
            imgurl = imgurls;
            _AutoGenFileName = autoGenFileName;
        }


        /// <summary> 
        /// 上传RAR文件 
        /// </summary> 
        public string UploadRARFile()
        {
            return DoUpload(ZIP_FILE);
        }

        /// <summary> 
        /// 上传视频文件 
        /// </summary> 
        public string UploadVideo()
        {
            return DoUpload(MUILT_MEDIA_FILE);
        }

        /// <summary> 
        /// 上传图片文件 
        /// </summary> 
        public string UploadImage()
        {
            return DoUpload(PICTURE_FILE);
        }



        /// <summary>
        /// 实现上传功能
        /// </summary>
        /// <param name="allowedExtensions">允许上传的文件类型</param>
        /// <returns></returns>
        private string DoUpload(string allowedExtensions)
        {
            ErrorLog.Log(commen.MapPath_mj("MJLogs/" + DateTime.Now.ToString("yyyyMMdd")), DateTime.Now.ToString() + "执行下载程序");
            bool fileOK = false;
            if (imgurl == "") return ""; //上传控件中如果不包含文件，退出 
            // 得到文件的后缀 
            string fileExtension = System.IO.Path.GetExtension(imgurl).ToLower();
            // 看包含的文件是否是被允许的文件后缀 
            fileOK = allowedExtensions.IndexOf(fileExtension) > 0;
            try
            {
                string imgurlfile = System.Configuration.ConfigurationManager.AppSettings["indexPic"];
                // 文件另存在服务器指定目录下 
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(imgurlfile)))
                {
                    //Directory是创建文件夹FileStream是写入和创建文件
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(imgurlfile));
                }
                string imgname = "product_" + DateTime.Now.ToString("yyyyMMDDhhmmssff") + ".png";
                string savefile = System.Web.HttpContext.Current.Server.MapPath(imgurlfile).Replace("~/", "") + "\\" + imgname;
                if (IsUploadImage(fileExtension))//保存图片
                {
                    WebRequest webreq = WebRequest.Create(imgurl);
                    WebResponse webres = webreq.GetResponse();
                    Stream stream = webres.GetResponseStream();
                    System.Drawing.Image output = System.Drawing.Image.FromStream(stream);
                    // 检查图片宽度/高度/大小 
                    if (this.IMG_MAX_WIDTH != 0 && output.Width > this.IMG_MAX_WIDTH)
                    {
                        output = CImageLibrary.GetOutputSizeImage(output, this.IMG_MAX_WIDTH);
                    }
                    Bitmap bmp = CImageLibrary.ChangeImgWH(130, 173, output);
                    bmp.Save(savefile, output.RawFormat);
                }
                _LastUploadedFile = imgurlfile.Replace("~/", "") + "\\" + imgname;;
                return _LastUploadedFile;
            }
            catch (Exception ex)
            {
                ErrorLog.Log(commen.MapPath_mj("MJLogs/" + DateTime.Now.ToString("yyyyMMdd")), DateTime.Now.ToString() + ex.Message); ;
                return "";
            }
        }




        public string UploadImage(int maxWidth, int maxHeight)
        {
            this.IMG_MAX_WIDTH = maxWidth;
            this.IMG_MAX_HEIGHT = maxHeight;
            return DoUpload(PICTURE_FILE);
        }

        /// <summary> 
        /// 上传任何支持的文件 
        /// </summary> 
        public string UploadAnySupported()
        {
            return DoUpload(PICTURE_FILE + ZIP_FILE + MUILT_MEDIA_FILE);
        }
        /// <summary>
        /// 获取中英文混排字符串的实际长度(字节数)
        /// </summary>
        /// <param name="str">要获取长度的字符串</param>
        /// <returns>字符串的实际长度值（字节数）</returns>
        public static int getStringLength(string str)
        {
            if (str.Equals(string.Empty))
                return 0;
            int strlen = 0;
            ASCIIEncoding strData = new ASCIIEncoding();
            //将字符串转换为ASCII编码的字节数字
            byte[] strBytes = strData.GetBytes(str); 
            for (int i = 0; i <= strBytes.Length - 1; i++)
            {
                if (strBytes[i] == 63)  //中文都将编码为ASCII编码63,即"?"号
                    strlen++;
                strlen++;
            }
            return strlen;
        }
    

        /// <summary> 
        /// 生成新的文件名 
        /// </summary> 
        private string GetNewFileName(string folder, string fileName)
        {
            //_AutoGenFileName==true 或者文件名长度>50,自动生成32位GUID文件名 
            if (_AutoGenFileName || getStringLength(fileName) >= 50)
            {
                string ext = System.IO.Path.GetExtension(fileName);
                string newfile = Guid.NewGuid().ToString().Replace("-", "") + ext;
                return folder + newfile;
            }
            else
            {
                if (System.IO.File.Exists(folder + fileName))
                {
                    string ext = System.IO.Path.GetExtension(fileName);
                    string filebody = fileName.Replace(ext, "");

                    int x = 1;
                    while (true) //如果文件存在，生成尾部带(x)的文件
                    {
                        string newfile = folder + filebody + "(" + x.ToString() + ")" + ext;
                        if (!System.IO.File.Exists(newfile))
                            return folder + filebody + "(" + x.ToString() + ")" + ext;
                        else
                            x++;
                    }
                }
                else
                    return folder + fileName;
            }
        }

        /// <summary> 
        /// 最大支持小于1MB的文件。 
        /// </summary> 
        private bool AllowMaxSize(int fileLength)
        {
            int MAX_SIZE_UPLOAD = 1024;//最大支持上传小于1MB的文件。 
            double kb = fileLength / 1024;
            return (int)kb < MAX_SIZE_UPLOAD;
        }
        
        /// <summary>
        /// 判断是否是指定的图片格式
        /// </summary>
        /// <param name="fileExtension"></param>
        /// <returns></returns>
        private bool IsUploadImage(string fileExtension)
        {
            bool isImage = PICTURE_FILE.IndexOf(fileExtension) > 0;
            return isImage;
        }
    }
}
